// 冒泡排序
function bubbleSort(arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    let flag = false // 发生交换的标志
    for (let j = 0; j < arr.length - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        flag = true
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
      }
    }
    // 没发生交换，直接退出
    if (!flag) break
  }
  return arr
}
// 选择排序
function selectionSort(arr) {
  let minIndex
  for (let i = 0; i < arr.length - 1; i++) {
    minIndex = i
    for (let j = minIndex + 1; j < arr.length; j++) {
      if (arr[i] < arr[minIndex]) {
        minIndex = i
      }
    }
    let temp = arr[i]
    arr[i] = arr[minIndex]
    arr[minIndex] = temp
  }
}
// 插入排序
function insertionSort(arr) {
  for (let i = 1; i < arr.length; i++) {
    let j = i - 1
    while (j >= 0 && arr[i] < arr[j]) {
      arr[j + 1] = arr[j]
      j--
    }
    arr[j + 1] = arr[i]
  }
}
// 归并排序
function mergetSort(arr, left, right, tempArr = []) {
  if (left >= right) return
  let mid = (left + right) >> 1
  mergetSort(arr, left, mid)
  mergetSort(arr, mid + 1, right)
  let l1 = left, r1 = mid, l2 = mid + 1, r2 = right
  let inx = left
  while (l1 <= r1 && l2 <= r2) {
    if (arr[l1] < arr[l2]) {
      tempArr[inx++] = arr[l1++]
    } else {
      tempArr[inx++] = arr[l2++]
    }
  }
  while (l1 <= r1) tempArr[inx++] = arr[l1++]
  while (l2 <= r2) tempArr[inx++] = arr[l2++]
  for (let i = left; i <= right; i++) {
    arr[i] = tempArr[i]
  }
}
let arr = [6, 3, 5, 9, 10]
// mergetSort(arr, 0, arr.length - 1)
// console.log(arr);
// 快速排序
function quickSort(arr, left, right) {
  let key = arr[left]
  let l = left, r = right
  while (l < r) {
    while (arr[r] > key && l < r) r--
    arr[l] = arr[r]
    while (arr[l] <= key && l < r) l++
    arr[r] = arr[l]
  }
  arr[l] = key
  if (l > left)
    quickSort(arr, left, l)
  if (r > l + 1)
    quickSort(arr, l + 1, right)
}
quickSort(arr, 0, arr.length - 1)
console.log(arr);

